package com.tanglongan.designPattern.dp21_template.demo02;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JdbcTemplate {

    private final DataSource dataSource;

    public JdbcTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public final List<?> executeQuery(String sql, RowMapper<?> rowMapper, Object[] values) throws Exception {
        try {
            //1、创建连接
            Connection connection = this.getConnection();
            //2、创建语句集
            PreparedStatement ps = this.createPreparedStatement(connection, sql);
            //3、执行语句集
            ResultSet rs = this.executeQuery(ps, values);
            //4、处理结果集
            List<?> result = this.parseResultSet(rs, rowMapper);
            //5、关闭结果集
            rs.close();
            //6、关闭语句集
            ps.close();
            //7、关闭连接
            connection.close();
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<?> parseResultSet(ResultSet rs, RowMapper<?> rowMapper) throws Exception {
        List<Object> result = new ArrayList<>();
        int rowNum = 0;
        while (rs.next()) {
            result.add(rowMapper.mapRow(rs, rowNum++));
        }
        return result;
    }


    private ResultSet executeQuery(PreparedStatement ps, Object[] values) throws SQLException {
        for (int i = 0; i < values.length; i++) {
            ps.setObject(i, values[i]);
        }
        return ps.executeQuery();
    }


    private PreparedStatement createPreparedStatement(Connection connection, String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }


    private Connection getConnection() throws SQLException {
        return this.dataSource.getConnection();
    }

}
